package com.china08.yxyapi.api.manage.stu.mystudy.huixue.exercise;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.config.RabbitConfig;
import com.china08.yxyapi.entity.es.ElasticYxyQuestionBankResource;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlan;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnow;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnowTrain;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnowTrainQues;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanQues;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.model.questionbank.YxyQuesBanQuestType1_2_3Model;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainQuesRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanQuesRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanRepository;
import com.china08.yxyapi.service.mg.impl.PlanExerciseServiceImpl;
import com.china08.yxyapi.service.mg.impl.YxyHuixuePlanCrtServiceImpl;
import com.china08.yxyapi.util.DateUtils;
import com.china08.yxyapi.util.SpringContextUtil;
import com.google.gson.Gson;

/**
 * 计划解答试题判断
 *
 */
@RestController
public class PlanExerciseJudgeController {

    @Autowired
    private PlanExerciseServiceImpl planExerciseServiceImpl;

    @Autowired
    private YxyHuixuePlanKnowTrainQuesRepository yxyHuixuePlanKnowTrainQuesRepository;

    @Autowired
    private YxyHuixuePlanQuesRepository yxyHuixuePlanQuesRepository;

    @Autowired
    private YxyHuixuePlanKnowRepository yxyHuixuePlanKnowRepository;

    @Autowired
    private YxyHuixuePlanRepository yxyHuixuePlanRepository;

    @Autowired
    private YxyHuixuePlanKnowTrainRepository yxyHuixuePlanKnowTrainRepository;

    @Autowired
    private YxyHuixuePlanCrtServiceImpl yxyHuixuePlanCrtServiceImpl;

    @RequestMapping(value = "/api_yw/manage/stu/mystudy/huixue/exercise/judge", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {

        BigDecimal bd;

        ElasticYxyQuestionBankResource question = planExerciseServiceImpl.getExerciseById(reqModel.quesId);

        YxyHuixuePlanKnow planKnow = yxyHuixuePlanKnowRepository.findTopByPkId(reqModel.pkId);

        List<YxyHuixuePlanKnow> planKnowLst = yxyHuixuePlanKnowRepository.findByPkId(reqModel.pkId);

        YxyHuixuePlan plan = yxyHuixuePlanRepository.findOne(planKnow.getPlanId());

        // 答题记录保存
        YxyHuixuePlanKnowTrain train = new YxyHuixuePlanKnowTrain();
        train.setId(plan.getStudentId() + plan.getId() + planKnow.getKnowId() + DateUtils.formatDate10(new Date()));
        train.setStudentId(plan.getStudentId());
        train.setPlanId(plan.getId());
        train.setBookContents(plan.getBookContentId());
        train.setKnowId(planKnow.getKnowId());
        train.setKnowName(planKnow.getKnowName());
        train.setCreatedDate(new Timestamp(new Date().getTime()));
        train = yxyHuixuePlanKnowTrainRepository.save(train);

        YxyHuixuePlanKnowTrainQues trainQues = new YxyHuixuePlanKnowTrainQues();
        trainQues.setTrainId(train.getId());
        trainQues.setStudentId(plan.getStudentId());
        trainQues.setPlanId(plan.getId());
        trainQues.setBookContents(plan.getBookContentId());
        trainQues.setKnowId(planKnow.getKnowId());
        trainQues.setKnowName(planKnow.getKnowName());
        trainQues.setQuesId(question.getId());
        trainQues.setCreatedDate(new Timestamp(new Date().getTime()));

        // 回答是否正确
        boolean quesResult = false;

        // 题型为单选 多选 判断
        if (question.getQuesType().equals("1") || question.getQuesType().equals("2")
                || question.getQuesType().equals("3")) {
            Gson gson = new Gson();
            YxyQuesBanQuestType1_2_3Model banQuestType1_2_3Model = gson.fromJson(question.getQuesBody(),
                    YxyQuesBanQuestType1_2_3Model.class);
            String answerTrue = banQuestType1_2_3Model.getQuesAnswer().getOptions();

            boolean flag = planExerciseServiceImpl.correctResult(answerTrue, reqModel.answer);
            if (flag) {
                quesResult = true;
            }
            trainQues.setAnswerOfMy(Arrays.asList(reqModel.answer.split("")));
            trainQues.setAnswerOfQues(Arrays.asList(answerTrue.split("")));
        } else {
            quesResult = reqModel.result;
        }

        // 修改试题权重
        YxyHuixuePlanQues huixuePlanQues = yxyHuixuePlanQuesRepository
                .findByStudentIdAndPlanIdAndQuesId(plan.getStudentId(), plan.getId(), question.getId());
        if (huixuePlanQues == null) {
            huixuePlanQues = new YxyHuixuePlanQues();
            huixuePlanQues.setStudentId(plan.getStudentId());
            huixuePlanQues.setPlanId(plan.getId());
            huixuePlanQues.setKnowId(planKnow.getKnowId());
            huixuePlanQues.setLevel(planKnow.getLevel());
            huixuePlanQues.setQuesId(question.getId());
            huixuePlanQues.setKnows(question.getKnowIds());
            if (quesResult) {
                huixuePlanQues.setWeight(0);
            } else {
                huixuePlanQues.setWeight(4);
            }
        } else {
            if (quesResult) {
                huixuePlanQues.setWeight(0);
            } else {
                huixuePlanQues.setWeight((huixuePlanQues.getWeight() - 1) <= 0 ? 5 : (huixuePlanQues.getWeight() - 1));
            }
        }
        yxyHuixuePlanQuesRepository.save(huixuePlanQues);

        // 掌握率是否提升
        boolean progressIsNot = false;
        // 掌握率 提升%
        double progressAdv = 0d;

        // 修改正确答题次数
        if (quesResult) {
            trainQues.setPassed(1);
            if (planKnow.getProgress() != 100d) {
                if (planKnow.getTrueTimes() == null) {
                    planKnow.setTrueTimes(0);
                }
                if (planKnow.getTrueTimes() + 1 == 3) {
                    for (YxyHuixuePlanKnow yxyHuixuePlanKnow : planKnowLst) {
                        yxyHuixuePlanKnow.setTrueTimes(0);
                        yxyHuixuePlanKnow.setLevel(planKnow.getLevel() + 1);

                        progressIsNot = true;
                        // 初始等级
                        Integer defLevel = yxyHuixuePlanCrtServiceImpl.getLevel(plan.getLastScore(),
                                Double.valueOf(plan.getLastScoreType()));
                        // 当前掌握率
                        double progress = (yxyHuixuePlanKnow.getLevel() - defLevel) * 1d
                                / (yxyHuixuePlanKnow.getGoalLevel() - defLevel) * 100;

                        bd = new BigDecimal(progress - yxyHuixuePlanKnow.getProgress());

                        progressAdv = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

                        bd = new BigDecimal(progress);
                        yxyHuixuePlanKnow.setProgress(bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }

                    // 权重初始化
                    List<YxyHuixuePlanQues> huixuePlanQuesLst = yxyHuixuePlanQuesRepository
                            .findByStudentIdAndPlanIdAndKnowId(plan.getStudentId(), plan.getId(), planKnow.getKnowId());
                    for (YxyHuixuePlanQues yxyHuixuePlanQues : huixuePlanQuesLst) {
                        yxyHuixuePlanQues.setWeight(5);
                        yxyHuixuePlanQuesRepository.save(yxyHuixuePlanQues);
                    }
                } else {
                    for (YxyHuixuePlanKnow yxyHuixuePlanKnow : planKnowLst) {
                        yxyHuixuePlanKnow.setTrueTimes(planKnow.getTrueTimes() + 1);
                    }

                }
            }
        } else {
            for (YxyHuixuePlanKnow yxyHuixuePlanKnow : planKnowLst) {
                yxyHuixuePlanKnow.setTrueTimes(0);
            }
            trainQues.setPassed(0);
        }
        trainQues.setUseTime(reqModel.time);

        yxyHuixuePlanKnowRepository.save(planKnowLst);
        yxyHuixuePlanKnowTrainQuesRepository.save(trainQues);

        if (progressAdv > 0) {
            SpringContextUtil.getBean(RabbitTemplate.class)
                    .convertAndSend(RabbitConfig.YW_HUIXUE_PLAN_CALCULATE_PROGRESS, plan.getId());
        }

        RespModel model = new RespModel();
        model.trainQuesId = trainQues.getId();
        if (progressIsNot) {
            model.progressIsNot = 1;
            model.progressAdv = progressAdv;
        } else {
            model.progressIsNot = 0;
        }
        return model;
    }

    /**
     * 请求参数
     * 
     */
    protected static class ReqModel extends YxyApiReqModel {
        // 知识点计划id
        public String pkId;
        // 试题id
        public String quesId;
        // 输入答案
        public String answer;
        // (主观题) 结果
        public boolean result;
        // 用时
        public String time;
    }

    /**
     * 响应参数
     * 
     */
    protected static class RespModel extends YxyApiRespModel {
        // 试题记录id
        public String trainQuesId;

        // 掌握率是否提升 0 未提升 1 已提升
        public Integer progressIsNot;

        // 掌握率 提升%
        public double progressAdv;
    }
}
